﻿using FirstLimitUpMode.Data;
using FirstLimitUpMode.Handles;
using FirstLimitUpMode.ViewModels;
using FirstLimitUpMode.Views;
using GpCommon.Helpers;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Xml.Linq;
using static GpCommon.Helpers.Win32Helper;

namespace FirstLimitUpMode
{
    /// <summary>
    /// MainView.xaml 的交互逻辑
    /// </summary>
    public partial class MainView : Window
    {
        public System.Threading.SynchronizationContext SynContent = null;

        private bool m_IsAppShow = true;
        private KeyboardHook _keyboardHook;
        private MainVModel m_VModel;
        public MainView()
        {
            InitializeComponent();
            SynContent = System.Threading.SynchronizationContext.Current;

            m_VModel = new MainVModel(this);
            this.DataContext = m_VModel;

            _keyboardHook = new KeyboardHook();
            _keyboardHook.SetHook();
            _keyboardHook.SetOnKeyDownEvent(Win32_Keydown);
            _keyboardHook.SetOnKeyUpEvent(Win32_Keyup);
        }

        private void TextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.Key == Key.Enter)
            {
                m_VModel.AddLockGpCommandExecute();
            }
        }

        //private void price5MoreItem_Click(object sender, RoutedEventArgs e)
        //{
        //    m_VModel.Is5More = !m_VModel.Is5More;
        //    price5MoreItem.Background = m_VModel.Is5More ? new SolidColorBrush(Colors.LightBlue) : new SolidColorBrush(Colors.White);
        //}
        private Key _lastKey = Key.None;
        private void Win32_Keydown(Key key)
        {
            if(key == Key.LeftAlt)
            {
                _lastKey = key; 
            }
            else if(_lastKey == Key.LeftAlt && key == Key.A)
            {
                if (this.Visibility == Visibility.Visible)
                {
                    this.Visibility = Visibility.Hidden;
                    IntPtr mainIntptr = Win32Helper.FindWindow(null, "网上股票交易系统5.0");
                    if (mainIntptr != IntPtr.Zero)
                    {
                        Win32Helper.ShowWindow(mainIntptr, Win32Helper.SW_HIDE);
                    }
                }
                else
                {
                    this.Visibility = Visibility.Visible;
                    IntPtr mainIntptr = Win32Helper.FindWindow(null, "网上股票交易系统5.0");
                    if (mainIntptr != IntPtr.Zero && m_IsAppShow)
                    {
                        Win32Helper.ShowWindow(mainIntptr, Win32Helper.SW_SHOW);
                    }
                }
            }
            else
            {
                _lastKey = Key.None;
            }
        }
        private void Win32_Keyup(Key key)
        {
            if(key == Key.LeftAlt)
            {
                _lastKey = Key.None;
            }
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            _keyboardHook.UnHook();
            TempData.WriteLockGps();
            //TempData.WriteDayByDayGps();
            m_VModel.SaveData();
            SettingsHelper.SaveSettings();
        }

        private bool IsShowSetting = true;
        private void SettingBtn_Click(object sender, RoutedEventArgs e)
        {
            if (IsShowSetting)
            {
                SettingPanel.Visibility = Visibility.Collapsed;
            }
            else
            {
                SettingPanel.Visibility = Visibility.Visible;
            }
            IsShowSetting = !IsShowSetting;
        }

        private void ModeChange_Click(object sender, RoutedEventArgs e)
        {
            m_VModel.IsFstMode = !m_VModel.IsFstMode;
            if(m_VModel.IsFstMode)
            {
                this.Title = "首板模式";
            }
            else
            {
                this.Title = "二板模式";
            }
        }

        private void OpenApp_Click(object sender, RoutedEventArgs e)
        {
            var path = SettingsHelper.GetStringByName(SettingConfine.GPAPP_PATH);
            if (string.IsNullOrEmpty(path))
            {
                SettingsHelper.SetValue(SettingConfine.GPAPP_PATH, "");
                return;
            }
            try
            {
                IntPtr mainIntptr = Win32Helper.FindWindow(null, "网上股票交易系统5.0");
                if (mainIntptr != IntPtr.Zero)
                {
                    Win32Helper.SwitchToThisWindow(mainIntptr, true);
                }
                else
                {
                    ProcessStartInfo processStartInfo = new ProcessStartInfo();
                    processStartInfo.FileName = path;
                    processStartInfo.WorkingDirectory = System.IO.Path.GetDirectoryName(path);
                    Process.Start(processStartInfo);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void WishList_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                OpenFileDialog openFileDialog = new OpenFileDialog();
                openFileDialog.Filter = "文本文件（*.txt）|*.txt";

                if (openFileDialog.ShowDialog() != true)
                    return;
                var content = File.ReadAllText(openFileDialog.FileName);
                if(string.IsNullOrEmpty(content)) return;
                TempData.WishGpList = content.Split(';').ToList();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void ShowCurSize_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var curList = new List<long>(HttpHelper.ResponseTotalSize);
                long totalBytes = 0;
                curList.ForEach(x => totalBytes += x);
                // 计算 GB
                long gb = totalBytes / (1024 * 1024 * 1024);

                // 计算剩余的字节数
                long remainingBytesAfterGB = totalBytes % (1024 * 1024 * 1024);

                // 计算 MB
                long mb = remainingBytesAfterGB / (1024 * 1024);

                // 计算剩余的字节数
                long remainingBytesAfterMB = remainingBytesAfterGB % (1024 * 1024);

                // 计算 KB
                long kb = remainingBytesAfterMB / 1024;

                // 计算剩余的字节数
                long b = remainingBytesAfterMB % 1024;

                var time = DateTime.Now - HttpHelper.StartTime;
                var ms = (int)time.TotalMinutes;
                var kb_m = totalBytes  / 1024;
                var num_m = curList.Count;
                if (ms > 0)
                {
                    kb_m /= ms;
                    num_m /= ms;
                }
                MessageBox.Show($"当前总响应量{gb} GB {mb} MB {kb} KB {b} B，平均响应速度{kb_m}KB每分钟" + "\r\n" +
                    $"当前总请求次数{curList.Count} 次，平均请求次数{num_m}次每分钟");
            }
            catch (Exception)
            {

            }
        }

        private void ShowOrHideApp_Click(object sender, RoutedEventArgs e)
        {
            IntPtr mainIntptr = Win32Helper.FindWindow(null, "网上股票交易系统5.0");
            if (mainIntptr != IntPtr.Zero)
            {
                // 检查窗口是否隐藏或最小化
                if(!IsWindowVisible(mainIntptr))
                {
                    Win32Helper.ShowWindow(mainIntptr, Win32Helper.SW_SHOW);
                }
                else
                {
                    Win32Helper.ShowWindow(mainIntptr, Win32Helper.SW_HIDE);
                }
            }

        }

        private void ShowLocalInfo_Click(object sender, RoutedEventArgs e)
        {
            GpLocalInfoView view = new GpLocalInfoView();
            view.Owner = this;
            view.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            view.Show();
        }
    }
}
